package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.myapplication.Bean.User;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private EditText usnedit, psdedit;
    private Button registerbtn, loginbtn;
    private TextView logintxt;
    List<User> list = new ArrayList<>();
    int userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        getUser();
        setListener();
    }

    private void initView() {
        usnedit = findViewById(R.id.usnedit);
        psdedit = findViewById(R.id.psdedit);
        registerbtn = findViewById(R.id.registerbtn);
        loginbtn = findViewById(R.id.loginbtn);
        logintxt = findViewById(R.id.logtxt);

    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (login()) {
                    logintxt.setText("登陆成功，id为：" + userid);
                } else {
                    logintxt.setText("登录失败");
                }
            }
        });
        registerbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User user=new User();
                user.setId(list.size());
                user.setUsername(usnedit.getText().toString());
                user.setPassword(psdedit.getText().toString());
                list.add(user);
                logintxt.setText("注册成功");

            }
        });
    }

    private void getUser() {
        User user1 = new User(0, "张三", "111");
        User user2 = new User(1, "李四", "222");
        User user3 = new User(2, "王五", "333");
        list.add(user1);
        list.add(user2);
        list.add(user3);
    }

    private boolean login() {
        boolean k = false;
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            if (usnedit.getText().toString().equals(user.getUsername())
                    && psdedit.getText().toString().equals(user.getPassword())) {
                userid = user.getId();
                k = true;
            }
        }
        return k;
    }
}
